//
//  CJPrePlayPageVIewController.m
//  CoJellyCartoon
//
//  Created by dllo on 16/4/5.
//  Copyright © 2016年 CJG. All rights reserved.
//

#import "CJPrePlayPageVIewController.h"
#import "CJPlayPageTableVIewCell.h"
#import "CJPlayPageHeader.h"
#import "CJPrePlayPageVIewModel.h"
#import "CJCommentModel.h"
#import "VideoPlayer.h"
#import "CJRelatesModel.h"
#import "UIButton+one.h"
#import "FinalPlayViewController.h"
#import "VideoInfo.h"
#import "CoreDataManager.h"
#import "CJRelatesModel.h"
#import "FinalPlayViewController.h"
#import <AFNetworking.h>
#define PREPLAYURL @"http://app.bilibili.com/x/view?_device=android&_hwid=53c9b4a7dd017094&aid=%@&appkey=c1b107428d337928&build=414000&plat=0&platform=android"
#define COMMENTURL @"http://api.bilibili.com/x/reply?_device=android&_hwid=53c9b4a7dd017094&appkey=c1b107428d337928&build=414000&oid=%@&platform=android&pn=%d&ps=20&sort=0&type=1&sign"

@interface CJPrePlayPageVIewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) CJPlayPageHeader *tableheader;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *titleLabel;
@property (nonatomic, strong) CJPlayPageTableVIewCell *cell;
@property (nonatomic, strong) CJPrePlayPageVIewModel *PrePlayPageViewModel;
@property (nonatomic, strong) CJCommentModel *commentModel;
@property (nonatomic, assign) int refreshNum;
@property (nonatomic, copy) NSString *Cid;
@property (nonatomic, copy) NSString *playUrl;
@property (nonatomic, strong) UITableView *forrefresh;
@property (nonatomic, strong) UIButton *PlayBtn;
@property (nonatomic, strong) UIBarButtonItem *CollectButton;
@property (nonatomic, strong) UIBarButtonItem *DownLoadButton;
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSMutableArray *coreDataArray;


@property (nonatomic, strong) VideoPlayer *player;
@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UILabel *startTimeLable;
@property (nonatomic, strong) UILabel *totalTimeLable;
@property (nonatomic, strong) UIView *TopView;
@property (nonatomic, strong) UIView *PlayToolView;
@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, assign) BOOL isTouch;
@property (nonatomic, strong) UISlider *timeSlider;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) UIButton *Playbutton;
@property (nonatomic, strong) NSString *headline;


@property (nonatomic, assign) BOOL isDown;//判断是否下载
@property (nonatomic, strong) NSMutableArray *downloadArray;//已下载文件数组
@property (nonatomic, strong) UILabel *downloadLabel;


@end

@implementation CJPrePlayPageVIewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"relateInfo" object:nil];
}
-(void)viewDidLoad{
    
    self.downloadLabel = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth - 100)/2, 200, 100, 40)];
    self.downloadLabel.backgroundColor = [UIColor blackColor];
    self.downloadLabel.alpha = 0.5;
    self.downloadLabel.textAlignment = NSTextAlignmentCenter;
    self.downloadLabel.textColor = [UIColor whiteColor];
    self.downloadLabel.layer.cornerRadius = 10;
    self.downloadLabel.layer.masksToBounds = YES;
    
    self.coreDataManager = [CoreDataManager shareCoreDtaManager];
    self.coreDataArray = [NSMutableArray arrayWithCapacity:0];
    //(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    
    
    [self creatTwoFunctionButton];
    self.refreshNum = 0;
    [self getPlayInfo];
    [self creatTableView];

    [self getCommentInfo];
    
    self.titleLabel = [UIButton buttonWithType:UIButtonTypeSystem];
    self.titleLabel.frame = CGRectMake(0, 0, 100, 30);
    [self.titleLabel setTitle:@"立即播放" forState:UIControlStateNormal];
    self.titleLabel.tintColor = [UIColor whiteColor];
    _titleLabel.titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.titleLabel.textColor = [UIColor whiteColor];
    
    [self.titleLabel addTarget:self action:@selector(startButtonAction:) forControlEvents:UIControlEventTouchUpInside];

//    [self setRefresh];
    self.navigationItem.titleView = _titleLabel;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getaid:) name:@"relateInfo" object:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"L20"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(Back)];
    
    

    
//    [self p_setRefresh];
    

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
   

//    [self creatPlayTools];
//    [self p_setRefresh];
    [self finalFirstRequest];
    [self finalSecondRequest];

}

-(void)creatTwoFunctionButton{
    self.CollectButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"uncollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(ToCollect:)];
    self.DownLoadButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"download"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(ToDownload:)];
    NSArray *array = @[self.CollectButton,self.DownLoadButton];
    self.navigationItem.rightBarButtonItems = array;
}

#pragma mark - 视图将要出现

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationItem.hidesBackButton = NO;
   
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"VideoInfo" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"aid LIKE %@",self.idString];
    
    [fetchRequest setPredicate:predicate];
    
    NSError *error;
    
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [self.coreDataArray setArray:fetchedObjects];
    if (fetchedObjects == nil) {
//        //(@"%@",error);
    }else{
        
        VideoInfo *videoinfo = [self.coreDataArray lastObject];
        if (videoinfo.aid == self.idString) {
            [self.CollectButton setImage:[[UIImage imageNamed:@"collected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        }else{
            [self.CollectButton setImage:[[UIImage imageNamed:@"uncollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        }
    }
//判断是否下载
    [self getData];
    //(@"数组%@", self.downloadArray);
    //(@"标题%@", self.headtitle);
    NSString *string = [self.headtitle stringByAppendingString:@".mp4"];
    
    for (int i = 0; i < self.downloadArray.count; i++) {
        //(@"iiii%@", self.downloadArray[i]);
        
        if ([string isEqualToString:self.downloadArray[i]]) {
            
            [self.DownLoadButton setImage:[[UIImage imageNamed:@"codownload"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
            
            self.isDown = YES;
            break;
        } else {
            [self.DownLoadButton setImage:[[UIImage imageNamed:@"download"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
            
            self.isDown = NO;
        }
    }
    
}

-(void)creatTableView{
    self.refreshNum = 0;
    
    [GiFHUD show];
    [GiFHUD setGifWithImageName:@"hold.gif"];
    
//    self.HeaderPic.image = [UIImage imageNamed:@"ic_category_t119"];
    self.tableheader = [[CJPlayPageHeader alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
    
    self.tableView  = [[UITableView alloc] initWithFrame:self.view.frame  style:UITableViewStylePlain];
    
    self.tableView.dataSource = self;
    self.tableView.delegate =self;
    
//    self.tableView.contentSize = CGSizeMake(0, self.view.bounds.size.height * 5);
    self.tableView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
    self.tableView.tableHeaderView = self.tableheader;
    self.tableView.bounces = NO;
//    self.tableView.scrollEnabled = NO;
    [self.tableView registerClass:[CJPlayPageTableVIewCell class] forCellReuseIdentifier:@"CJPlayPageTableVIewCell"];
    [self.view addSubview:self.tableView];
    self.HeaderPic.frame = CGRectMake(0, -200, self.view.frame.size.width, 200);
    self.isPlay = NO;
    self.isTouch = YES;
  
    
     [_tableView addSubview:_HeaderPic];
    [self.tableheader.changeContent addTarget:self action:@selector(ChangeContent:) forControlEvents:UIControlEventValueChanged];
    
    
}

-(void)getPlayInfo{
    
    [WZAFNetTool GetNetWithURL:[NSString stringWithFormat:PREPLAYURL,self.idString] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
//        //(@"%@",self.idString);
            self.PrePlayPageViewModel = [[CJPrePlayPageVIewModel alloc] initWithDataSource:reuslt[@"data"]];
        
        [GiFHUD dismiss];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)getCommentInfo{
    
    [WZAFNetTool GetNetWithURL:[NSString stringWithFormat:COMMENTURL, self.idString,self.refreshNum] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
        
        self.commentModel = [[CJCommentModel alloc] initWithDictionary:reuslt[@"data"]];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"CJPlayPageTableVIewCell"];
    
    self.cell.segment = self.tableheader.changeContent;
    
    self.cell.commnetModel = self.commentModel;
    
    self.cell.prePlayModel = self.PrePlayPageViewModel;
    
    return self.cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return self.view.bounds.size.height;
    
}
-(void)ChangeContent : (UISegmentedControl *)change{
    
    self.cell.PrePlayCollectionView.contentOffset = CGPointMake(change.selectedSegmentIndex * self.view.bounds.size.width, 0);
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
  
    CGFloat yoffset = scrollView.contentOffset.y;
    CGFloat xoffset = (yoffset + 200) * 2;
    
    if (yoffset< -200) {
        CGRect rect = _HeaderPic.frame;
        rect.origin.y = yoffset;
        rect.size.height = -yoffset;
        rect.origin.x = xoffset;
        rect.size.width = self.view.frame.size.width + fabs(xoffset)*2;
        _HeaderPic.frame = rect;
        
    }
    
    CGFloat alpha = (yoffset + 150) / 150;
    
     [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor colorWithRed:0.969 green:0.345 blue:0.533 alpha:1.000] colorWithAlphaComponent:alpha]]forBarMetrics:UIBarMetricsDefault];
    
    _titleLabel.alpha = alpha;
    
}

- (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    //    开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    //    获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //    使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //    渲染上下文
    CGContextFillRect(context, rect);
    //    从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    //    结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
    
    
}

-(void)p_setRefresh{
    
    __weak CJPrePlayPageVIewController *PrePlayVC = self;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        self.refreshNum += 1;
        
        [PrePlayVC setRefresh:self.refreshNum];
        
        [self.forrefresh.mj_footer beginRefreshing];
        
    }];
    //空闲状态
    [footer setTitle:@"空闲状态" forState:MJRefreshStateIdle];
    //正在刷新状态
    [footer setTitle:@"正在刷新状态 ..." forState:MJRefreshStateRefreshing];
    //没有跟多数据
    [footer setTitle:@"没有跟多数据" forState:MJRefreshStateNoMoreData];
    //    footer.stateLabel.textColor = kAppearanceColor;
    self.forrefresh.mj_footer = footer;
    
    [self.forrefresh.mj_footer beginRefreshing];
    
}

-(void)getaid:(NSNotification *)message{
    
    
    
    CJRelatesModel *relateModel = message.userInfo[@"relateInfo"];
    
    _idString = [NSString stringWithFormat:@"%@",relateModel.aid];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"VideoInfo" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"aid LIKE %@",self.idString];
    
    [fetchRequest setPredicate:predicate];
    
    NSError *error;
    
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [self.coreDataArray setArray:fetchedObjects];
    if (fetchedObjects == nil) {
        
    }else{
        
        VideoInfo *videoinfo = [self.coreDataArray lastObject];
        if (videoinfo.aid == self.idString) {
            [self.CollectButton setImage:[[UIImage imageNamed:@"collected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        }else{
            [self.CollectButton setImage:[[UIImage imageNamed:@"uncollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        }
    }
    
    
    [self getPlayInfo];
    
    self.picURL = relateModel.pic;
    
    [_HeaderPic sd_setImageWithURL:[NSURL URLWithString:self.picURL] placeholderImage:[UIImage imageNamed:@"zhanweiye"]];
    
    [self getCommentInfo];
    
}
-(void)setRefresh:(int)num{
    
    [self getCommentInfo];
    
}

- (void)startButtonAction:(UIButton *)sender {
    FinalPlayViewController *final = [[FinalPlayViewController alloc] init];
    final.Aid = self.idString;
    [self presentViewController:final animated:YES completion:^{
        
    }];
}

-(void)setPicURL:(NSString *)picURL{
    _picURL = picURL;
    self.HeaderPic = [PictureView shareImageView];
    
    [self.HeaderPic sd_setImageWithURL:[NSURL URLWithString:picURL] placeholderImage:[UIImage imageNamed:@"zhanweiye"]];
    
    self.Playbutton = [UIButton shareButton];
    self.Playbutton.frame =CGRectMake(0, -200, self.view.frame.size.width, 200);
    
    [self.Playbutton addTarget:self action:@selector(startButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_tableView addSubview:self.Playbutton];
    
    [self.tableView reloadData];
}



#pragma mark - 数据请求播放网址
- (void)finalFirstRequest {
    [WZAFNetTool GetNetWithURL:[NSString stringWithFormat:@"http://www.bilibilijj.com/Api/AvToCid/%@", self.idString] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
        
        self.headline = reuslt[@"title"];
        //(@"标题2333%@", self.headline);
        NSArray *arr = reuslt[@"list"];
        NSDictionary *dic = arr[0];
        self.Cid = [dic objectForKey:@"CID"];
        [self finalSecondRequest];
    } failure:^(NSError *error) {
        
    }];
    
    
}
#pragma mark - 解最后播放网址
- (void)finalSecondRequest {
    [WZAFNetTool GetNetWithURL:[NSString stringWithFormat:@"http://interface.bilibili.com/playurl?platform=android&_device=android&_hwid=831fc7511fa9aff5&_tid=0&_p=1&_down=0&quality=3&otype=json&appkey=86385cdc024c0f6c&type=mp4&sign=7fed8a9b7b446de4369936b6c1c40c3f&_aid=%@&cid=%@", self.idString, self.Cid] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
        
        NSArray *arr = reuslt[@"durl"];
        NSDictionary *dic = arr[0];
        self.playUrl = [dic objectForKey:@"url"];
        
        [self.player playWithUrl:[NSString stringWithFormat:@"%@",self.playUrl]];
        [self.player play];
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark-收藏
-(void)ToCollect:(UIBarButtonItem *)click{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"VideoInfo" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"aid == %@",self.idString];
    [fetchRequest setPredicate:predicate];
    
    NSError *error;
    
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
   
        [self.coreDataArray setArray:fetchedObjects];
        
        VideoInfo *videoinfo = [self.coreDataArray lastObject];
    
        if (videoinfo.aid == self.idString) {
            [self.coreDataManager.managedObjectContext deleteObject:videoinfo];
            [self.coreDataManager saveContext];
            
            [MBProgressHUD showSuccess:@"取消收藏"];

            
            [self.CollectButton setImage:[[UIImage imageNamed:@"uncollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        }else{
            
            VideoInfo *videoinfO = [NSEntityDescription insertNewObjectForEntityForName:@"VideoInfo" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            videoinfO.title = self.PrePlayPageViewModel.title;
            videoinfO.aid = self.idString;
            videoinfO.pic = self.picURL;
            
            [self.coreDataManager saveContext];
            
            [MBProgressHUD showSuccess:@"已收藏"];
            
            [self.CollectButton setImage:[[UIImage imageNamed:@"collected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
            
        }
    

    
}

#pragma mark - 播放功能

-(void)creatPlayer{
    
    self.player = [VideoPlayer shareAVPlayer];
    self.player.volume = 1.0f;
    [self.player play];
    
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200) ];
    self.playView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.playView];

    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    
    self.playerLayer.frame = self.playView.frame;
    
    [self.playView.layer addSublayer:self.playerLayer];
    self.playerLayer.videoGravity = AVLayerVideoGravityResize;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTouchesRequired = 1;
    
    tap.numberOfTouchesRequired = 1;
    
    [self.HeaderPic addGestureRecognizer:tap];
    
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}
- (void)creatTopView{
    self.TopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    self.TopView.backgroundColor = [UIColor colorWithWhite:0.835 alpha:1.000];
    self.TopView.alpha = 0.5;
    [self.playView addSubview:self.TopView];
}

-(void)creatPlayToolView{
    self.PlayToolView = [[UIView alloc] initWithFrame:CGRectMake(0, self.playView.frame.size.height - 40, self.view.frame.size.width, 40)];
    self.PlayToolView.alpha = 0.5;
    self.PlayToolView.backgroundColor = [UIColor colorWithWhite:0.835 alpha:1.000];
    
    [self.playView addSubview:self.PlayToolView];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playButton.frame = CGRectMake(5, 0, 40, 40);
    [self.playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    [self.playButton addTarget:self action:@selector(playBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.PlayToolView addSubview:self.playButton];
    
    
    self.startTimeLable = [[UILabel alloc] initWithFrame:CGRectMake(55, 0, 60, 40)];
    self.startTimeLable.font = [UIFont systemFontOfSize:15];
    self.startTimeLable.backgroundColor = [UIColor clearColor];
    
    [self.PlayToolView addSubview:self.startTimeLable];
    
    self.totalTimeLable = [[UILabel alloc] initWithFrame:CGRectMake(self.PlayToolView.frame.size.width - 50, 0, 50, 40)];
    self.totalTimeLable.font = [UIFont systemFontOfSize:15];
    self.totalTimeLable.backgroundColor = [UIColor clearColor];
    [self.PlayToolView addSubview:self.totalTimeLable];
    
    self.timeSlider = [[UISlider alloc] initWithFrame:CGRectMake(105, 5, 200, 30)];
    self.timeSlider.maximumValue = 1.0f;
    self.timeSlider.minimumValue = 0.0f;
    
    [self.timeSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    [self.PlayToolView addSubview:self.timeSlider];
}

-(void)tapAction: (UITapGestureRecognizer *)tap{
    if (self.isTouch) {
        self.TopView.hidden = NO;
        self.PlayToolView.hidden = NO;
        
        self.isTouch = NO;
    }else{
        self.TopView.hidden = YES;
        self.PlayToolView.hidden = YES;
        self.isTouch = YES;
    }
}

-(void)playBtnAction:(UIButton *)click{
    
    if (click.selected) {
        [self.player play];
        [self.playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        click.selected = NO;
        
    }else{
        
        [self.player pause];
        
        [self.playButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        click.selected = YES;
    }
}

-(void)sliderAction: (UISlider *)change{
    if (self.player.currentItem.duration.value) {
        [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value / self.player.currentItem.duration.timescale * self.timeSlider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self.player play];
        }];
    }
}

-(void)timerAction{
    CMTime presentTime = self.player.currentItem.currentTime;
    CMTime totalTime = self.player.currentItem.duration;
    
    CGFloat presentFloatTime = (CGFloat)presentTime.value / presentTime.timescale;
    CGFloat presentFloatTotalTime = (CGFloat)totalTime.value / totalTime.timescale;
    
    self.timeSlider.value = presentFloatTime / presentFloatTotalTime;
    
    NSDate *presentDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTime];
    NSDate *totalTimeDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTotalTime];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (presentFloatTotalTime / 3600 >=1) {
        
        [formatter setDateFormat:@"HH:mm:ss"];
        
    }else{
        
        [formatter setDateFormat:@"mm:ss"];
    }
    
    NSString *presentStrTime = [formatter stringFromDate:presentDate];
    NSString *totalStrTime = [formatter stringFromDate:totalTimeDate];
    
    self.startTimeLable.text = presentStrTime;
    self.totalTimeLable.text = totalStrTime;
    
    if (presentStrTime == totalStrTime) {
        
        [self.playView removeFromSuperview];
    }
    
}

- (BOOL)shouldAutorotate
{
    return YES;
}
//-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
//    return UIInterfaceOrientationMaskLandscape;
//}
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
//{
//    return UIInterfaceOrientationLandscapeLeft;
//}


-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        CGSize screen = [UIScreen mainScreen].bounds.size;
        self.playView.frame = CGRectMake(0, 0, screen.width, 200.0);
        self.playerLayer.frame = self.playView.frame;
        self.TopView.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
        self.PlayToolView.frame = CGRectMake(0, self.playView.frame.size.height - 40, self.view.frame.size.width, 40);
        self.timeSlider.frame = CGRectMake(105, 5, 200, 30);
        self.totalTimeLable.frame = CGRectMake(self.PlayToolView.frame.size.width - 50, 0, 50, 40);
        if (screen.width > screen.height) {
            //(@"横屏");
            self.playView.frame = CGRectMake(0, 0, self.view.frame.size.width,414);
            self.playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            self.TopView.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
            self.PlayToolView.frame = CGRectMake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 40);
            self.timeSlider.frame = CGRectMake(105, 5, 500, 30);
            self.totalTimeLable.frame = CGRectMake(self.PlayToolView.frame.size.width - 50, 0, 50, 40);
            
        }else{
            //(@"竖屏");
        }
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        //        self.TopView.backgroundColor = [UIColor orangeColor];
        //(@"横屏完处理");
    }];
}
-(void)MiniPlayer:(UIButton *)click{
    
//    [self.player play];
    
//    [self.HeaderPic removeFromSuperview];
    
//    [click removeFromSuperview];
    

}
-(void)ToDownload:(UIBarButtonItem *)click{
//    //(@"网址%@", self.playUrl);
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status ) {
        if (status == 2) {
            [self downFlieFromSever];
        }else if (status == 1){
            [self downFlieFromSever];
        }else{
            [MBProgressHUD showError:@"无网络"];
        }
    }];

    
}

-(void)downFlieFromSever{
    
    if (self.isDown) {
        self.downloadLabel.hidden = NO;
        self.downloadLabel.text = @"正在下载";
        [self.view addSubview:self.downloadLabel];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.downloadLabel.hidden = YES;
        });
        
    } else {
        self.downloadLabel.text = @"已经下载";
        [self.view addSubview:self.downloadLabel];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.downloadLabel.hidden = YES;
        });
        
        
        [self.DownLoadButton setImage:[[UIImage imageNamed:@"codownload"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        self.isDown = YES;
        
        if (self.playUrl) {
        NSURL *url = [NSURL URLWithString:self.playUrl];
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
            
            NSURLSession *session = [NSURLSession sharedSession];
            
            NSURLSessionDownloadTask *downLoad = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                
                if (error) {
                    //(@"error = %@", error.localizedDescription);
                } else {
                    //            //(@"%@", location);
                }
                // 如果要保存文件,需要将文件保存至沙盒
                // 1. 根据URL获取到下载的文件名
                NSString *fileName = [self.headline lastPathComponent];
                // 2. 生成沙盒的路径
                NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                
                NSString *path = [docs[0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", fileName]];
                
                //(@"下载路径^^  %@", path);
                
                NSURL *toURL = [NSURL fileURLWithPath:path];
                
                // 3. 将文件从临时文件夹复制到沙盒,在iOS中所有的文件操作都是使用NSFileManager
                if (location == nil) {
//                    [MBProgressHUD showError:@"无网络"];
                    return ;
                }
                [[NSFileManager defaultManager] copyItemAtURL:location toURL:toURL error:nil];
                
                
                // 4. 显示下载完成lable
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    self.downloadLabel.text = @"下载成功";
                    [self.view addSubview:self.downloadLabel];
                    
                    [self.DownLoadButton setImage:[[UIImage imageNamed:@"codownload"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
                    
                    
                    //延时之行一段代码
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        self.downloadLabel.hidden = YES;
                        
                        
                        
                    });
                    
                });
                self.isDown = YES;
                
            }];
            
            //4.因为任务默认是挂起状态，需要恢复任务（执行任务）
            [downLoad resume];

        }else{
            return;
        }
        
        
}
    

}

- (void)getData {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //(@"=,=%@", paths);
    NSString *docDirectory = [paths objectAtIndex:0];
    

    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSArray *files = [fm subpathsAtPath:docDirectory];
    
    self.downloadArray = [NSMutableArray arrayWithCapacity:0];
    
    for (NSString *str in files) {
        if ([str hasSuffix:@"mp4"]) {
            [self.downloadArray addObject:str];
        }
    }

}
-(void)Back{
    [self.navigationController popViewControllerAnimated:YES];
    
}




@end
